#将图片的大小变化
gm = require('gm').subClass({imageMagick:true})
GridStore = require('mongoose').mongo.GridStore
fsdb = require('../config').fsdb.db
fs = require('fs')
ObjectID = require('mongodb').ObjectID


#从mongodb中获取图片，并且修改图片的大小，保存到新的路径
#注意，如果已经存在，那么会删除之前已经存在的图片
exports.resize = (_src,width,filename,cb) ->
  gs = new GridStore(fsdb,_src,'r')
  #首先删除相应的代码
  gs.open (err,gs) ->
    if err
      return cb err
    #首先删除相应的数据（如果已经存在）
    content_type = gs.contentType || 'image/jpeg'
    GridStore.unlink fsdb, filename, (err, gridStore) ->
      return cb err if err
      stream = gs.stream(true)
      #由于暂时没有办法直接使gm直接读取流，所以先落地到本地，让gm从本地读取
      #如果是windows  可能需要变更路径
      _tmp_filename = '/tmp/' + _src
      w_stream = fs.createWriteStream(_tmp_filename)
      stream.pipe(w_stream)
      stream.on 'error',(err)->
        return cb err
      stream.on 'end',()->
        #修改图片的大小
        gm(_tmp_filename).resize(width).noProfile().autoOrient().toBuffer (err,buffer)->
          if err
            return cb err
          _id2 = new ObjectID()
          gridStore = new GridStore(fsdb, _id2, filename, "w",{content_type:content_type})
          gridStore.open (err,gridStore)->
            if err
              return cb err
            gridStore.write buffer,(err,gridStore) ->
              if err
                return cb err
              gridStore.close (err,filedata)->
                if err
                  return cb err
                fs.unlink _tmp_filename,(err)->
                  if err
                    console.log('failed to delete tmp file')
                data = {}
                data._id = _id2
                data.filename = filename
                cb err,data


